package com.youbenzi.dockerpool;

import java.util.List;
import java.util.Random;

import redis.clients.jedis.Jedis;

/**
 * 注册中心
 * @author yangyingqiang
 */
public class Register {

	private static final String DATA_KEY = "data";
	private static final String NUM_KEY = "num";
	
	/**
	 * 注册一个docker连接
	 * @param key 连接关键词
	 * @param host 连接的host
	 * @param port 连接的端口
	 */
	public static void registe(String key, String host, int port) {
		Jedis jedis = jedis();
		jedis.rpush(dataKey(key, host), port + "");
		jedis.close();
	}
	
	/**
	 * 获取一个可用的docker 端口
	 * @param key 连接关键词
	 * @param host 连接的host
	 * @return
	 */
	public static String use(String key, String host) {
		Jedis jedis = jedis();
		String port = jedis.rpop(dataKey(key, host));
		jedis.close();
		return port;
	}
	
	/**
	 * 释放一个docker连接数
	 * @param key
	 * @param host
	 */
	public static void release(String key, String host) {
		Jedis jedis = jedis();
		jedis.decr(numKey(key, host));
		jedis.close();
	}
	/**
	 * 登记一个docker连接数
	 * @param key
	 * @param host
	 */
	public static void increase(String key, String host) {
		Jedis jedis = jedis();
		jedis.incr(numKey(key, host));
		jedis.close();
	}
	
	/**
	 * 获取某个key-host 的docker 连接数
	 * @param key
	 * @param host
	 * @return
	 */
	public static int num(String key, String host) {
		Jedis jedis = jedis();
		String value = jedis.get(numKey(key, host));
		jedis.close();
		try {
			return Integer.parseInt(value);
		} catch (NumberFormatException e) {
			return 0;
		}
	}
	
	/**
	 * 获取未被使用的端口
	 * @param key
	 * @param host
	 * @return
	 */
	public static int unregisteredPort(String key, String host) {
		Jedis jedis = jedis();
		List<String> ports = jedis.lrange(dataKey(key, host), 0, -1);
		int tmp = Config.dockerPortRange[1] - Config.dockerPortRange[0] + 1;
		Random random = new Random();
		int port = random.nextInt(tmp) + Config.dockerPortRange[0];
		while (ports.contains(port + "")) {
			port = random.nextInt() + Config.dockerPortRange[0];
		}
		return port;
	}
	
	private static Jedis jedis() {
		return new Jedis(Config.redisHost, Config.redisPort);
	}
	
	private static String dataKey(String key, String host) {
		return DATA_KEY + "_" + key + "_" + host;
	}
	
	private static String numKey(String key, String host) {
		return NUM_KEY + "_" + key + "_" + host;
	}

	public static void main(String[] args) {
		Config.dockerPortRange = new int[]{9001, 9999};
		Config.redisHost = "127.0.0.1";
		Config.redisPort = 6379;
		System.out.println(unregisteredPort("jdk7", "127.0.0.1"));
	}
}
